package cn.bbstone.pisces2.ui.job;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.ICoreRunnable;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.e4.ui.di.UISynchronize;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(immediate = true)
public class JobServiceImpl implements JobService {
	private static Logger log = LoggerFactory.getLogger(JobServiceImpl.class);

	private List<Job> jobs = new ArrayList<>();

	public JobServiceImpl() {
	}

	public Job newJob(UISynchronize sync, String jobName, IJobTask task, Runnable callback) {
		// startup job for load file list data
		Job job = Job.create(jobName, monitor -> {
			// ----- doLongThing
			// NOTICE: server startup task will blocked here, following code will not execute continue.
			task.doTask(); 
			
			// ------ syncWithUi
//			sync.asyncExec(callback);
			sync.asyncExec(() -> {
				log.info("run in asyncExec() .....");
			});

			return Status.OK_STATUS;
		});
//		job.setUser(true);
		// Start the Job
		job.schedule();

		jobs.add(job);
		return job;
	}

	public Job newJobWithProgress(UISynchronize sync, String jobName, String taskName, IJobTask task,
			Runnable callback) {
		// startup job for load file list data
		Job job = Job.create(jobName, (ICoreRunnable) monitor -> {
			monitor.beginTask(taskName, 100);
			task.doTask();
//			SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
			// convert to SubMonitor and set total number of work units
			// do something long running
//			List<FileListItem> dataList = new ArrayList<FileListItem>(); // fileListService.findAll();
			monitor.worked(30);
//			subMonitor.split(30);

//			subMonitor.setWorkRemaining(70);
			// ...
			// If you want to update the UI
			sync.asyncExec(callback);
		});
		// if set rule, will used progress bar exclusive
		job.setRule(ResourcesPlugin.getWorkspace().getRoot());
//		job.setUser(true);
		// Start the Job
		job.schedule();

		jobs.add(job);
		return job;
	}

	public void cancelJobs() {
		for (Job job : jobs) {
			job.cancel();
		}
	}

}
